//
//  CaptrueViewController.m
//  PetAPP
//
//  Created by apple on 16/3/2.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "CaptrueViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "CapTrueVCPushPage.h"

#define  SCREENWIDTH [UIScreen mainScreen].bounds.size.width
#define  SCREENHEIGHT [UIScreen mainScreen].bounds.size.height

@interface CaptrueViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, retain) AVCaptureSession *session;

@property (nonatomic, retain) UIImageView *line;

@end

@implementation CaptrueViewController

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    if (self.session) {
        [self.session startRunning];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    if ([AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]) {
        [self createSubViews];
        [self setOverlayPickerView];
    }else {
    
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲，由于您没有摄像头不支持此功能哦!" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
            
        }];
        [alert addAction:actionOK];
        //  模态推出.
        [self presentViewController:alert animated:YES completion:^{}];
    
    }
}



- (void)createSubViews {

    //获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //创建输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //这个CGRect参数和普通的Rect范围不太一样，它的四个值的范围都是0-1，表示比例。
    //CGRectMake(上面往下计算的垂直距离，从左往右的水平距离，高度的百分比，宽度的百分比)
    [output setRectOfInterest:CGRectMake(0.27,0.09,0.46, 0.82)];
    
    //初始化链接对象
    self.session = [[[AVCaptureSession alloc]init] autorelease];
    //高质量采集率
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [self.session addInput:input];
    [self.session addOutput:output];
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = self.view.layer.bounds;
    
    [self.view.layer insertSublayer:layer atIndex:0];
    
    [self.session addObserver:self forKeyPath:@"running" options:NSKeyValueObservingOptionNew context:nil];
    //开始捕获
    [self.session startRunning];

}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        //[session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        
        [self.session stopRunning];

        CapTrueVCPushPage *captrue = [[CapTrueVCPushPage alloc] init];
        [self.navigationController pushViewController:captrue animated:YES];
        [captrue release];
        captrue.webUrl = metadataObject.stringValue;
        
    }
}


/** 观察者功能实现 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    if ([object isKindOfClass:[AVCaptureSession class]]) {
        BOOL isRunning = ((AVCaptureSession *)object).isRunning;
        if (isRunning) {
            /** 添加动画效果 */
            self.line.hidden = NO;
            CABasicAnimation *animation = [CaptrueViewController moveYTime:2 fromY:[NSNumber numberWithFloat:0] toY:[NSNumber numberWithFloat:SCREENWIDTH-60-2] rep:OPEN_MAX];
            [self.line.layer addAnimation:animation forKey:@"LineAnimation"];
        }else{
            /** 移除动画效果 */
            [self.line.layer removeAnimationForKey:@"LineAnimation"];
            self.line.hidden = YES;
        }
    }

}

/** 动画效果实现 */
+ (CABasicAnimation *)moveYTime:(float)time fromY:(NSNumber *)fromY toY:(NSNumber *)toY rep:(int)rep {
    
    CABasicAnimation *animationMove = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    [animationMove setFromValue:fromY];
    [animationMove setToValue:toY];
    animationMove.duration = time;
    animationMove.delegate = self;
    animationMove.repeatCount  = rep;
    animationMove.fillMode = kCAFillModeForwards;
    animationMove.removedOnCompletion = NO;
    animationMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    return animationMove;
}

- (void)setOverlayPickerView{
    //左侧的view
    UIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, SCREENHEIGHT)];
    [self.view addSubview:leftView];
    [leftView release];
    leftView.alpha = 0.3;
    leftView.backgroundColor = [UIColor blackColor];
    
    //右侧的view
    UIImageView *rightView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREENWIDTH - 30, 0, 30, SCREENHEIGHT)];
    [self.view addSubview:rightView];
    [rightView release];
    
    rightView.alpha = 0.3;
    rightView.backgroundColor = [UIColor blackColor];
    
    //最上部view
    UIImageView *upView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 0, SCREENWIDTH - 60, (self.view.center.y - (SCREENWIDTH - 60) / 2))];
    [self.view addSubview:upView];
    [upView release];
    
    upView.alpha = 0.3;
    upView.backgroundColor = [UIColor blackColor];
    
    //底部view
    UIImageView * downView = [[UIImageView alloc] initWithFrame:CGRectMake(30, (self.view.center.y +(SCREENWIDTH - 60) / 2), (SCREENWIDTH - 60), (SCREENHEIGHT - (self.view.center.y - (SCREENWIDTH - 60) / 2)))];
    [self.view addSubview:downView];
    [downView release];
    downView.alpha = 0.3;
    downView.backgroundColor = [UIColor blackColor];
    
    UIImageView *centerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH - 60, SCREENWIDTH - 60)];
    [self.view addSubview:centerView];
    [centerView release];
    centerView.center = self.view.center;
    centerView.image = [UIImage imageNamed:@"capborder"];
    centerView.contentMode = UIViewContentModeScaleAspectFit;
    centerView.backgroundColor = [UIColor clearColor];
    /** 扫描的线 */ //CGRectGetMaxY获取到上方图层的下边距
    self.line = [[UIImageView alloc] initWithFrame:CGRectMake(30, CGRectGetMaxY(upView.frame), SCREENWIDTH- 60, 2)];
    [self.view addSubview:_line];
    [_line release];
    self.line.image = [UIImage imageNamed:@"capline"];
    self.line.contentMode = UIViewContentModeScaleAspectFill;
    self.line.backgroundColor = [UIColor clearColor];
    
    /** 提示文本 */
    UILabel *msg = [[UILabel alloc] initWithFrame:CGRectMake(30, CGRectGetMinY(downView.frame), SCREENWIDTH - 60, 60)];
    [self.view addSubview:msg];
    [msg release];
    msg.backgroundColor = [UIColor clearColor];
    msg.textColor = [UIColor whiteColor];
    msg.textAlignment = NSTextAlignmentCenter;
    msg.font = [UIFont systemFontOfSize:16];
    msg.text = @"将二维码放入框内,即可自动扫描";
    
    
    /** 贝塞尔曲线设置毛玻璃 */
    UIBezierPath *backgroundPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 3, 40, 40) cornerRadius:20];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:leftButton];
    leftButton.frame = CGRectMake(10, 40, 40, 40);
    leftButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [leftButton addTarget:self action:@selector(handleBackButton) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"backForCap"] forState:UIControlStateNormal];
    
    leftButton.layer.shadowPath = backgroundPath.CGPath;
    leftButton.layer.shadowOpacity = 0.4;
    leftButton.layer.shadowRadius = 0;
    leftButton.layer.shadowColor = [UIColor blackColor].CGColor;
    
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(self.view.frame.size.width - 50, 40, 40, 40);
    rightButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [rightButton addTarget:self action:@selector(systemLightSwitch:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setImage:[UIImage imageNamed:@"shoudianOpen"] forState:UIControlStateSelected];
    [rightButton setImage:[UIImage imageNamed:@"shoudianClose"] forState:UIControlStateNormal];
    [self.view addSubview:rightButton];
    
    rightButton.layer.shadowPath = backgroundPath.CGPath;
    rightButton.layer.shadowOpacity = 0.4;
    rightButton.layer.shadowRadius = 0;
    rightButton.layer.shadowColor = [UIColor blackColor].CGColor;

    
    
}

/** 退后按钮 */
- (void)handleBackButton {
    [self.session removeObserver:self forKeyPath:@"running" context:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

/** 手电按钮点击事件 */
- (void)systemLightSwitch:(UIButton *)button {
    button.selected = !button.selected;
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        if (button.selected) {
            [device setTorchMode:AVCaptureTorchModeOn];
        } else {
            [device setTorchMode:AVCaptureTorchModeOff];
        }
        [device unlockForConfiguration];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
